package com.example.myweb.Domain.Entity;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import javax.persistence.*;
import java.time.LocalDateTime;


/**
 * 记录用户对投票的每一次投票行为
 */
@Entity
@Table(
        name = "poll_votes",
        // 在数据库层面建立联合唯一约束，确保一个用户对一个投票只能投一次
        uniqueConstraints = {
                @UniqueConstraint(columnNames = {"attachment_id", "user_id"})
        }
)
@Data
public class PollVote {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long voteId;

    /**
     * 关联到 attachments 表中的投票实体 (一个投票可以有多个投票记录)
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "attachment_id", nullable = false)
    @ToString.Exclude // 避免循环引用
    @EqualsAndHashCode.Exclude
    private Attachment attachment;

    /**
     * 关联到投票的用户 (一个用户可以参与多个投票)
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    @ToString.Exclude
    @EqualsAndHashCode.Exclude
    private User user;

    /**
     * 用户选择的选项索引 (从0开始)
     */
    @Column(name = "option_index", nullable = false)
    private int optionIndex;

    /**
     * 投票时间
     */
    @Column(name = "vote_time", nullable = false, updatable = false)
    private LocalDateTime voteTime;

    /**
     * 在实体被持久化之前，自动设置投票时间
     */
    @PrePersist
    protected void onCreate() {
        this.voteTime = LocalDateTime.now();
    }
}